#coding:utf-8

import threading
import random
import time
from biquge.util import getSoup
from tingshu.DBUtil import checkIsExist
from tingshu.DBUtil import insertNovel
from tingshu.DBUtil import insertNovelItem
from tingshu.DBUtil import delNovel
from biquge.util import dataToDictionaries
from tingshu.BrowserUtil import getHtml




class myThread (threading.Thread):   #继承父类threading.Thread
    def __init__(self, threadID, name,url,base_url):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.url = url
        self.baseUrl = base_url
    def run(self):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        print ("Starting " + self.name)
        insertContentToDB(self.url,self.baseUrl)
        print ("Exiting " + self.name)


#往数据库里面倒入数据
def insertContentToDB(url,base_url):

    content_soup = getSoup(url)
    # 有声小说标题
    title = content_soup.find(class_="tit").find('h1').text.replace('有声小说', '')

    # 根据小说名称查看小说是否存在，如果存在跳过本次♻️，如果不存在继续♻️
    if checkIsExist(title):
        print("有声小说" + title + " 已经存在,不再继续爬取数据")
        return

    spans = content_soup.find(class_="zz").find_all('span')
    # 有声小说作者
    anthor = spans[0].find('a').text
    # 有声小说主播
    auchor = spans[1].find('a').text
    # 有声小说封面
    imgUrl = content_soup.find(class_="r-img").find('img').get('src')
    # 有声小说简介
    introduction = content_soup.find(class_="jj").find('p').text
    # 有声小说类型
    dqwz = content_soup.find(class_="dqwz")
    type = dqwz.find_all('a')[1].text

    t = time.time()
    int_t = str(int(t))
    id = ''.join(str(i) for i in random.sample(range(0, 9), 9)) + int_t

    type_id = dataToDictionaries(type)
    # 往数据库里面插入有声小说
    insertNovel(id, title, imgUrl, auchor, anthor, type_id, introduction)

    jj_list = content_soup.find(id="vlink_1").find_all('a')

    i = 0
    # 章节集合
    for item in jj_list:
        i = i + 1
        # 标题
        item_title = item.text
        # 获取章节内容
        item_url = base_url + item.get('href')
        item_html = getHtml(item_url, 5)
        # 章节url
        zj_url = item_html.find(id='jp_audio_0').get('src')
        #排除无效的小说
        if zj_url.find('key')>0:
            #删除数据库小说记录
            delNovel(id)
            break
        insertNovelItem(item_title, id, i, zj_url)


